package com.marktim.pokerpoker.server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import android.os.Handler;
import android.os.Looper;

public class Client {

	private Socket socket;
	private ClientListener listener;
	private Handler uiHandler;

	private static final int SERVERPORT = 1406;
	private static final String SERVER_IP = "192.168.1.147";

	public Client() {
		uiHandler = new Handler(Looper.getMainLooper());
		new Thread(new ClientThread()).start();
		
	}
	
	public void setListener(ClientListener listener) {
		this.listener = listener;
	}

	public void sendToServer(String command) {
		try {
			PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
			out.println(command);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	class ClientThread implements Runnable {

		@Override
		public void run() {

			try {
				InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

				socket = new Socket(serverAddr, SERVERPORT);

				new Thread(new CommunicationThread(socket)).start();
			} catch (UnknownHostException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			}

		}

	}
	
	class CommunicationThread implements Runnable {

		private Socket socket;

		private BufferedReader input;

		public CommunicationThread(Socket socket) {

			this.socket = socket;

			try {

				this.input = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));

			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		public void run() {

			while (!Thread.currentThread().isInterrupted()) {

				try {

					final String read = input.readLine();
					if (listener != null) {
						uiHandler.post(new Runnable() {

							@Override
							public void run() {
								listener.onMessage(read);
							}
							
						});
					}

					
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}
	
	public interface ClientListener  {
		public void onMessage(String message);
	}

}
